package org.tao.lightningmq.broker.utils;

import java.io.*;

/**
 * @Author lht
 * @date 2025/1/3 - 16:50
 * @description: 文件读写工具
 */
public class FileContentUtil {

    public static String readFromFile(String path) {
        try(BufferedReader bufferedReader = new BufferedReader(new FileReader(path))) {
            StringBuilder sb = new StringBuilder();
            while (bufferedReader.ready()) {
                sb.append(bufferedReader.readLine());
            }
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeToFile(String path, String content) {
        try(FileWriter fileWriter = new FileWriter(path)) {
            fileWriter.write(content);
            fileWriter.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void createFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    throw new RuntimeException("新建文件失败，文件路径：" + filePath);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
